package com.dchh.android.suverynew.act;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.LevelSelectAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.views.DKOperateWindow;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.File;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.db.Sqlite.RecordDBManager;
import com.dhcc.android.base.gis.FactoryGPS;
import com.dhcc.android.base.gis.SelectItemChangedListener;
import com.dhcc.android.base.gis.TouchLongToolCommen;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.DKMapUtil;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import srs.Display.Symbol.TextSymbol;
import srs.Geometry.Envelope;
import srs.Geometry.FormatConvert;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Geometry.IPoint;
import srs.Layer.CommonLayer;
import srs.Rendering.CommonRenderer;
import srs.Utility.sRSException;
import srs.tools.MapControl;
import srs.tools.ZoomInCommand;
import srs.tools.ZoomOutCommand;

/**
 * 自然地块选择
 *
 * @author zhoudan
 * @date 2016年1月7日
 */
public class DKSelectActivity extends SBaseActivity {

    // 页面组件
    private LinearLayout main;
    /**
     * 层级目录
     */
    private TextView title;//
    /**
     * 层级选择目录布局
     */
    private LinearLayout titleLayout;
    /**
     * 地图布局
     */
    private LinearLayout selectListLayout;
    private ListView selectListview;
    private TextView selectClose;
    private TextView tv_GPSInfo = null;

    // 相关操作
    /**
     * 新增地块
     */
    private LinearLayout addBtn;
    /**
     * 合并地块
     */
    private LinearLayout hebingBtn;
    /**
     * 指南针
     */
    private LinearLayout zhinanzhen;
    /**
     * 多地块填报
     */
    private LinearLayout mutiReprot;


    /**
     * 右上角操作图标
     */
    private RelativeLayout imagebtn;
    /**
     * 作物照片拍摄
     */
    private LinearLayout zuowuimg;
    /**
     * 图纸拍摄
     */
    private LinearLayout tuzhiimg;

    /**
     * 任务名称
     */
    private String taskName;
    /**
     * 空间信息全局变量
     */
    public final static String GEO = "GEO";
    private MapControl dkSelectMapControl;

    // 选择列表的数据
    /**
     * 层级列表格式化数据
     */
    private List<Map<String, String>> levelList = new ArrayList<Map<String, String>>();
    /**
     * 原始数据
     */
    private List<Map<String, String>> dataList = null;
    private LevelSelectAdapter adapter;
    /**
     * 数据库管理工具
     */
    public static DBManagerUtil dBManagerUtil;
    /**
     * 样方编号主键
     */
    public static String YFBHU = "";
    public static String surveyDKIDPath;
    /**
     * 任务包路径
     */
    public static String root;
    /**
     * 路径
     */
    private String navtitle;
    /**
     * 路径
     */
    private String yfbh;
    /**
     * 地块工具类
     */
    DKMapUtil dkMapUtil;

    private boolean tz_flag;
    private boolean hb_flag;
    private boolean cf_flag;
    private boolean sc_flag;

    private String periodLabel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dk_level_select);
    }

    /**
     * @param context
     * @param view
     */
    private void configMap(Context context) {

        // add 杨宗仁 定位，放大，缩小按钮
        LayoutParams sp_params1 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams sp_params2 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams sp_params3 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ImageView btnZoomin = new ImageView(context);
        ImageView btnZoomout = new ImageView(context);
        ImageView ivLocationCenter = new ImageView(context);
        btnZoomin.setImageResource(R.mipmap.zoom_in);
        btnZoomout.setImageResource(R.mipmap.zoom_out);
        ivLocationCenter.setImageResource(R.mipmap.gps_recieved);

        btnZoomin.setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);
        btnZoomout.setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);
        ivLocationCenter
                .setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);

        sp_params1.width = Constants.screenWidth / 11;
        sp_params1.height = Constants.screenWidth / 11;
        sp_params1.bottomMargin = Constants.screenWidth / 11 + 32;
        sp_params1.rightMargin = 16;
        sp_params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        btnZoomin.setLayoutParams(sp_params1);

        sp_params2.width = Constants.screenWidth / 11;
        sp_params2.height = Constants.screenWidth / 11;
        sp_params2.rightMargin = 16;
        sp_params2.bottomMargin = 16;
        sp_params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        btnZoomout.setLayoutParams(sp_params2);

        sp_params3.width = Constants.screenWidth / 11;
        sp_params3.height = Constants.screenWidth / 11;
        sp_params3.leftMargin = 16;
        sp_params3.bottomMargin = 30;
        sp_params3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params3.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        ivLocationCenter.setLayoutParams(sp_params3);

        dkSelectMapControl.setGravity(Gravity.BOTTOM);

        dkSelectMapControl.addView(btnZoomin);
        dkSelectMapControl.addView(btnZoomout);
        dkSelectMapControl.addView(ivLocationCenter);
        if (btnZoomin != null) {
            btnZoomin.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ZoomInCommand zoomin = new ZoomInCommand();
                            zoomin.setBuddyControl(dkSelectMapControl);
                            zoomin.setEnable(true);
                            zoomin.onClick(v);
                    }
                    return true;
                }
            });
        }
        if (btnZoomout != null) {
            btnZoomout.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ZoomOutCommand zoomout = new ZoomOutCommand();
                            zoomout.setBuddyControl(dkSelectMapControl);
                            zoomout.setEnable(true);
                            zoomout.onClick(v);
                    }
                    return true;
                }
            });
        }

        if (ivLocationCenter != null) {
            ivLocationCenter.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    CommenUtil.SetLocationCenter(dkSelectMapControl);
                    return true;
                }
            });
        }

        if (tv_GPSInfo == null) {
            tv_GPSInfo = new TextView(this);
        }
        tv_GPSInfo.setTextColor(Color.BLACK);
        tv_GPSInfo.setBackgroundColor(Color.argb(128, 255, 255, 255));

        dkSelectMapControl.addView(tv_GPSInfo,
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);

        try {

            FactoryGPS factory = new FactoryGPS(tv_GPSInfo, null, null, null,
                    CommenUtil.getMapControl());
            FactoryGPS.NaviStart = false;
            factory.StartStopGPS(this, tv_GPSInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    OnClickListener viewClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.common_nav) {
                selectListLayout.setVisibility(View.VISIBLE);
            } else if (v.getId() == R.id.close) {
                selectListLayout.setVisibility(View.GONE);
            }
        }
    };

    private void getView() {
        // 获取视图组件
        title = (TextView) main.findViewById(R.id.common_title);
        title.setText(navtitle);
        titleLayout = (LinearLayout) main.findViewById(R.id.common_nav);
        selectListLayout = (LinearLayout) main.findViewById(R.id.select_list_layout);
        selectListview = (ListView) main.findViewById(R.id.select_listview);
        selectClose = (TextView) main.findViewById(R.id.close);

        addBtn = (LinearLayout) main.findViewById(R.id.add_operate);
        addBtn.setVisibility(View.VISIBLE);
        hebingBtn = (LinearLayout) main.findViewById(R.id.hebing_operate);
        if (hb_flag) {
            hebingBtn.setVisibility(View.VISIBLE);
        } else {
            hebingBtn.setVisibility(View.GONE);
        }

        LayoutParams rl = new LayoutParams(Constants.screenWidth / 5,
                LayoutParams.WRAP_CONTENT);
        rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rl.leftMargin = 10;
        selectListLayout.setLayoutParams(rl);
        // 设置列表点选监听
        selectListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                // 改变选中item的样式
                adapter.setSelect(position);
                adapter.notifyDataSetChanged();
                itemSelected(position, false);
            }
        });

        // 新增地块
        addBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isFastDoubleClick(500)) {
                    return;
                }
                File file = new File();
                String table = CommenUtil.getTableName("样方自然地块", periodLabel);
                file.setTable(table);
                file.setPfeild("YFBHU");
                dkMapUtil.addDK(file);
            }
        });
        // 合并地块
        hebingBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });

        if (adapter == null) {
            adapter = new LevelSelectAdapter(this, levelList);
            adapter.setIconFlag(true);
            selectListview.setAdapter(adapter);
        }
        selectListLayout.setVisibility(View.GONE);

        titleLayout.setOnClickListener(viewClick);
        selectClose.setOnClickListener(viewClick);

        //指南针
        zhinanzhen = (LinearLayout) main.findViewById(R.id.zhinanzhen_operate);
        zhinanzhen.setVisibility(View.VISIBLE);
        zhinanzhen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DKSelectActivity.this, CompassActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });
        //多地块单一作物统一填报
        mutiReprot = (LinearLayout) main.findViewById(R.id.muti_operate);
        mutiReprot.setVisibility(View.VISIBLE);
        mutiReprot.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DKSelectActivity.this, MutiDKReportActivity.class);
                intent.putExtra("YFBHU", YFBHU);
                intent.putExtra("navtitle", navtitle);
                intent.putExtra("yfbh", yfbh);
                intent.putExtra("taskName", taskName);
                intent.putExtra("title", getToolbarTitle());
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });
    }

    /**
     * 列表或者地图点选
     *
     * @param position 选中的item索引
     * @param isMap    是否为地图点选
     */
    public void itemSelected(final int position, boolean isMap) {
        // 地图自动缩放
        zoomInDKView(position);
        Map<String, String> map = dataList.get(position);
        DKOperateWindow pw = new DKOperateWindow(this, map);
        pw.show(title, cf_flag, sc_flag, onoperate);
    }


    /**
     * 图层放大 add by duanwg
     *
     * @param index 所选的图层的顺序号
     */
    public void zoomInDKView(int index) {

        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        String table = CommenUtil.getTableName("样方自然地块", periodLabel);

        String[] str = {"GEO", "YFDKBH", "COMPLETE"};
        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
        Constants.displayLableNames.clear();
        Constants.displayRenderBreaks.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }

                    double breakValue = 0;
                    breakValue = Double.valueOf(map.get("COMPLETE"));
                    Constants.displayRenderBreaks.add(breakValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //-----设置为分段渲染
        Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
        Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
        try {
            Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
        } catch (sRSException e) {
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
            System.out.println("地块图层分段渲染有误！");
            e.printStackTrace();
        }
        //-----设置分段渲染完毕

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);
        //((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
        // 地图控件
        IEnvelope env = Constants.COMMONLAYER.getGeometry(index).Extent();
        env = new Envelope(env.XMin() - env.Width() / 10, env.YMin() - env.Height() / 10,
                env.XMax() + env.Width() / 10, env.YMax() + env.Height() / 10);
        dkSelectMapControl.getActiveView().FocusMap().setExtent(env);

        // 高亮显示
        IPoint centerPoint = null;
        try {
            if (CommenUtil.IsListSelected) {
                centerPoint = Constants.COMMONLAYER.getGeometry(index).CenterPoint();
            } else {
                centerPoint = Constants.TargetPointTouch;
            }
            CommenUtil.setLightSelected(Constants.COMMONLAYER, index, (MapControl) CommenUtil.getMapControl(),
                    centerPoint);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 刷新图层
        dkSelectMapControl.Refresh();

    }

    DKOperateWindow.OnOperateClickListener onoperate = new DKOperateWindow.OnOperateClickListener() {

        /**
         * 面积填报
         */
        @Override
        public void OnReport(Map<String, String> data) {
            Dialog dialog = MyLoadingDialog.createLoadingDialog(DKSelectActivity.this, "正在载入，请稍后...");
            Constants.DIALOG = dialog;
            Constants.DIALOG.show();

            Constants.select = data;
            // 获取当前范围自然地块的图片
            Constants.ZRDKBITMAP = dkSelectMapControl.getBitmap();

            Intent intent = new Intent(DKSelectActivity.this, MyDemandActivity.class);
            intent.putExtra("YFBHU", YFBHU);
            startActivity(intent);
        }

        /**
         * 地块拆分
         */
        @Override
        public void OnChaifen(Map<String, String> data) {

            Constants.select = data;
            File file = new File();
            String table = CommenUtil.getTableName("样方自然地块", periodLabel);
            file.setTable(table);
            file.setPfeild("YFBHU");
            // 地块分割
            dkMapUtil.setCFDKObj(data);
            dkMapUtil.clipDK(file);
        }

        /**
         * 地块删除
         */
        @Override
        public void OnShanChu(final Map<String, String> data) {

            final AlertDialog alert = new AlertDialog(DKSelectActivity.this, "确定要删除选中的地块吗？", "删除", "取消");
            alert.setClicklistener(new AlertDialog.ClickListenerInterface() {

                @Override
                public void doConfirm() {
                    alert.dismiss();
                    Constants.select = data;
                    File file = new File();
                    String table = CommenUtil.getTableName("样方自然地块", periodLabel);
                    file.setTable(table);
                    file.setPfeild("YFBHU");
                    dkMapUtil.setCFDKObj(data);
                    boolean f = dkMapUtil.delDK(file, dkSelectMapControl, surveyDKIDPath);
                    if (f) {
                        //保存进度记录
                        RecordDBManager rcdDB = new RecordDBManager(DKSelectActivity.this);
                        rcdDB.add(data.get("DKBHU"), YFBHU, "3", "003");

                        //刷新数据
                        getData();
                        adapter.refresh(levelList);
                        delDKRefrensh();
                        dkSelectMapControl.Refresh();
                    }
                }

                @Override
                public void doCancel() {
                    alert.dismiss();
                }
            });
            alert.show();


        }
    };

    /**
     * 删除地块后的刷新
     */
    private void delDKRefrensh() {
        // 计算geometrys
        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        String table = CommenUtil.getTableName("样方自然地块", periodLabel);

        String[] str = {"GEO", "YFDKBH", "COMPLETE"};
        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
        Constants.displayLableNames.clear();
        Constants.displayRenderBreaks.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }


                    String breaks = map.get("COMPLETE");
                    double breakValue = 0;
                    breakValue = Double.valueOf(breaks);
                    Constants.displayRenderBreaks.add(breakValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                12f, false, Color.BLACK));


        //-----设置为分段渲染
        Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
        Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
        try {
            Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
        } catch (sRSException e) {
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
            System.out.println("地块图层分段渲染有误！");
            e.printStackTrace();
        }
        //-----设置分段渲染完毕

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);
        //((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);

    }


    private void mapView() {
        getData();
        // 刷新列表数据
        adapter.setSelect(-1);
        adapter.refresh(levelList);

        // 计算geometrys
        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        String table = CommenUtil.getTableName("样方自然地块", periodLabel);

        String[] str = {"GEO", "YFDKBH", "COMPLETE"};
        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
        Constants.displayLableNames.clear();
        Constants.displayRenderBreaks.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }

                    String breaks = map.get("COMPLETE");
                    double breakValue = 0;
                    breakValue = Double.valueOf(breaks);
                    Constants.displayRenderBreaks.add(breakValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                12f, false, Color.BLACK));

        //-----设置为分段渲染
        Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
        Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
        try {
            Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
        } catch (sRSException e) {
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
            System.out.println("地块图层分段渲染有误！");
            e.printStackTrace();
        }
        //-----设置分段渲染完毕

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);

        // 地图控件
        IEnvelope env = CommenUtil.getMap().getExtent();
        dkSelectMapControl = (MapControl) main.findViewById(R.id.mapmain);

        dkSelectMapControl.getActiveView().FocusMap(CommenUtil.getMap());
        CommenUtil.getMap().setExtent(env);

        CommenUtil.getMap().setDeviceExtent(
                new Envelope(0, 0, dkSelectMapControl.getWidth(), dkSelectMapControl.getHeight()));
        // 刷新图层
        dkSelectMapControl.Refresh();

        /** 增加地图点选事件 */
        /** CommenLayer的点击事件 */
        TouchLongToolCommen touchLongTool = new TouchLongToolCommen(Constants.COMMONLAYER);
        dkSelectMapControl.ClearDrawTool();
        touchLongTool.setBuddyControl(dkSelectMapControl);// mapControl为操作的地图控件
        touchLongTool.onClick(dkSelectMapControl);
        touchLongTool.setEnable(true);
        // 设置不累计选择项目
        touchLongTool.IsOnlyOneTime = false;
        // 设置是不为单选
        touchLongTool.IsOnlyOneSelect = false;
        // 设置选中或未选中条目时，触发的事件
        touchLongTool.zoom2Selected = new SelectItemChangedListener() {

            @Override
            public void doEventSettingsChanged(Object tar) {
                Integer index = (Integer) tar;
                System.out.println("####点选的自然地块顺序号：" + index);

                adapter.setSelect(index);
                adapter.notifyDataSetChanged();
                itemSelected(index, true);
            }
        };
        dkSelectMapControl.setDrawTool(touchLongTool);
    }

    private void getData() {
        String pfield = "YFBHU";
        // 获取数据库中当前层级的下级数据列表
        String[] fields = {"COMPLETE", "DKBHU", "YFDKBH", "YFBHU", "TBLXMC", "CUNMC", "CUNDM", "rowid", "GEO"};
        try {
            DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
            String tablename = CommenUtil.getTableName("样方自然地块", periodLabel);
            if (YFBHU == null) {
                dataList = DBImportUtil.listData(tablename, fields, null, null);
            } else {
                dataList = DBImportUtil.listData(tablename, fields, pfield, YFBHU);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "操作外部数据库出错", Toast.LENGTH_SHORT).show();
        }

        setTitle("样方" + yfbh + "的自然地块 (共" + dataList.size() + "个)");

        // 格式化原始数据
        levelList.removeAll(levelList);
        for (Map<String, String> map : dataList) {
            Map<String, String> m = new HashMap<String, String>();
            m.put("id", map.get("DKBHU"));
            String v = map.get("YFDKBH");
            m.put("name", v);
            m.put("icon", map.get("COMPLETE"));

            levelList.add(m);
        }
    }

    private void goBack() {
        if (StringUtil.isFastDoubleClick(500)) {
            return;
        }
        try {
            CommenUtil.getMap().getElementContainer().ClearElement();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // 从map 中删除commonLayer
            if (Constants.COMMONLAYER.getName() != null) {
                CommenUtil.getMap().RemoveLayer(Constants.COMMONLAYER);
            }

        } catch (sRSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Constants.data_refresh) {
            Constants.data_refresh = false;
            getData();
            adapter.refresh(levelList);
        }

        // 计算geometrys
        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        String table = CommenUtil.getTableName("样方自然地块", periodLabel);

        String[] str = {"GEO", "YFDKBH", "COMPLETE"};
        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
        Constants.displayLableNames.clear();
        Constants.displayRenderBreaks.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }


                    String breaks = map.get("COMPLETE");
                    double breakValue = 0;
                    breakValue = Double.valueOf(breaks);
                    Constants.displayRenderBreaks.add(breakValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                12f, false, Color.BLACK));


        //-----设置为分段渲染
        Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
        Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
        try {
            Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
        } catch (sRSException e) {
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
            System.out.println("地块图层分段渲染有误！");
            e.printStackTrace();
        }
        //-----设置分段渲染完毕

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);

        dkSelectMapControl.Refresh();
    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        tz_flag = SPreferencesManager.getValue(MSApplication.DK_TZ, false);
        hb_flag = SPreferencesManager.getValue(MSApplication.DK_HB, false);
        cf_flag = SPreferencesManager.getValue(MSApplication.DK_CF, false);
        sc_flag = SPreferencesManager.getValue(MSApplication.DK_SC, false);
        periodLabel = Constants.getTempData(DKSelectActivity.this, MSApplication.PERIOD_LABEL);
        // 等价于YFBHU
        YFBHU = getIntent().getStringExtra("pvalue");
        navtitle = getIntent().getStringExtra("navtitle");
        // 样方编号，对应下拉列表的下标
        yfbh = getIntent().getStringExtra("yfbh");
        taskName = getIntent().getStringExtra("taskName");
        surveyDKIDPath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";
        setTitle("样方" + yfbh + "的自然地块");
        // // 初始化CommonLayer
        Constants.COMMONLAYER = new CommonLayer();
        try {
            CommenUtil.getMap().AddLayer(Constants.COMMONLAYER);
        } catch (IOException e) {
            e.printStackTrace();
        }
        getView();
        mapView();
        dBManagerUtil = DBManagerUtil.getInstance(surveyDKIDPath, DKSelectActivity.this);
        dkMapUtil = new DKMapUtil(this, dBManagerUtil, Constants.select, dkSelectMapControl);
        StringUtil.dismissDialog(Constants.DIALOG);
        configMap(this);
    }

    @Override
    protected void onDestroy() {
        new MSApplication().deleteActivity(this);
        super.onDestroy();
    }

    OnClickListener backListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            goBack();
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
        }
        return true;
    }


    /**
     * 新增或拆分自然地块之后，刷新自然图斑，同时显示新增或拆分后的自然地块编号
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            default:
                // 计算geometrys
                DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
                String table = CommenUtil.getTableName("样方自然地块", periodLabel);

                String[] str = {"GEO", "YFDKBH", "COMPLETE"};
                final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
                Constants.displayLableNames.clear();
                Constants.displayRenderBreaks.clear();
                if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
                    boolean isFirst = true;
                    try {
                        for (Map<String, String> map : entityList) {
                            String wkt = map.get("GEO");

                            if (StringUtil.isNotEmpty(wkt)) {
                                IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                                if (geo != null) {
                                    if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                        isFirst = false;
                                        Constants.geometrys.clear();
                                    }
                                    Constants.geometrys.add(geo);
                                }
                            }
                            String LableID = "";
                            LableID = map.get("YFDKBH");

                            if (LableID != null) {
                                Constants.displayLableNames.add(LableID);
                            }


                            String breaks = map.get("COMPLETE");
                            double breakValue = 0;
                            breakValue = Double.valueOf(breaks);
                            Constants.displayRenderBreaks.add(breakValue);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                        12f, false, Color.BLACK));


                //-----设置为分段渲染
                Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
                Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
                try {
                    Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
                } catch (sRSException e) {
                    ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
                    System.out.println("地块图层分段渲染有误！");
                    e.printStackTrace();
                }
                //-----设置分段渲染完毕

                Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, Constants.displayRenderBreaks,
                        srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);
                dkSelectMapControl.getActiveView().FocusMap(CommenUtil.getMap());
                //			CommenUtil.getMap().setExtent(env);

                CommenUtil.getMap().setDeviceExtent(
                        new Envelope(0, 0, dkSelectMapControl.getWidth(), dkSelectMapControl.getHeight()));
                // 刷新图层
                dkSelectMapControl.Refresh();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.dk_select_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.zuowu:
                intent = new Intent(DKSelectActivity.this, ZWPhotoActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("yfbh", yfbh);
                startActivity(intent);
                break;
            case R.id.tuzhi:
                intent = new Intent(DKSelectActivity.this, YFTZPhotoActivity.class);
                intent.putExtra("from", 0);
                intent.putExtra("yfbh", yfbh);
                intent.putExtra("period", periodLabel);
                intent.putExtra("taskName", taskName);
                startActivity(intent);
                break;
        }
        return true;
    }
}
